import '../lib/jquery.js'
import { $messageTip, $axios } from './util.js'

const axios = $axios()

// 注册用户
function userRegister() {
  const user = {
    username: $('.username').val(),
    password: $('.password').val(),
    rpassword: $('.rpassword').val(),
    nickname: $('.nickname').val()
  };

  let msgPre = ''
  const keyMap = {
    username: '用户名',
    password: '密码',
    rpassword: '确认密码',
    nickname: '昵称'
  }

  for (const key in user) {
    if (user[key] === '') {
      msgPre = keyMap[key] + '不能为空';
      break;
    }
  }

  if (msgPre !== '') {
    $messageTip(msgPre);
    return;
  }

  const data = JSON.stringify(user);

  axios.post('/users/register', data, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => {
    if (response.data) {
      const responseData = JSON.parse(response.data);

      if (responseData.code === 1) {
        if (confirm('注册成功，跳转登录页面')) {
          setTimeout(() => {
            window.location.href = './login.html';
          })
        }
      } else {
        $messageTip(responseData.message);
      }
    }
  }).catch(error => {
    console.log(error);
  });
}

$('button').on('click', function () {
  userRegister();
});
